package com.crm.business.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.crm.business.admin.service.AdminFileService;
import com.crm.business.crm.mapper.CrmLargeScreenSettingMapper;
import com.crm.business.crm.service.CrmLargeScreenSettingService;
import com.crm.business.crm.service.CrmPageService;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.entity.BO.CrmLargeScreenSettingBO;
import com.crm.common.crm.entity.BO.CrmLargeScreenSettingSaveBO;
import com.crm.common.crm.entity.BO.CrmLargeScreenSettingSearchBO;
import com.crm.common.crm.entity.PO.CrmLargeScreenSetting;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.common.ka.core.servlet.upload.*;
import com.crm.business.utils.BaseUtil;
import com.crm.business.utils.UserUtil;
import com.crm.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

/**
 * <p>
 * 线索表 服务实现类
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-05-21
 */
@Service
@Slf4j
public class CrmLargeScreenSettingServiceImpl extends BaseServiceImpl<CrmLargeScreenSettingMapper, CrmLargeScreenSetting> implements CrmLargeScreenSettingService, CrmPageService {

    @Autowired
    private CrmLargeScreenSettingMapper crmLargeScreenSettingMapper;

    private UploadConfig.LocalConfig config;

    @Autowired
    private AdminFileService adminFileService;

    @Qualifier("adminThreadPoolExecutor")
    @Autowired
    private Executor executor;

    private static final String JOIN_STR = "-";
    private String checkStatus = "waiting";

    @Override
    public BasePage<CrmLargeScreenSettingBO> queryList(CrmLargeScreenSettingSearchBO search) {
        Integer pageStart = search.getPage() > 0 ? (search.getPage() - 1) * search.getLimit() : 0;
        search.setPageStart(pageStart);
        Integer count = getBaseMapper().queryPageListCount(search);
        if(count == 0){
            BasePage<CrmLargeScreenSettingBO> basePage = new BasePage<>(search.getPage(),search.getLimit());
            return basePage;
        }
        List<CrmLargeScreenSettingBO> crmLargeScreenSettingList = getBaseMapper().queryList(search);
        BasePage<CrmLargeScreenSettingBO> basePage = new BasePage<>(search.getPage(),search.getLimit(),count);
        basePage.setList(crmLargeScreenSettingList);
        return basePage;
    }

    /**
     * 新增修改大屏配置
     * @param crmModel
     */
    public void addOrUpdate(CrmLargeScreenSettingSaveBO crmModel){
        CrmLargeScreenSetting crmLargeScreenSetting = BeanUtil.copyProperties(crmModel.getEntity(), CrmLargeScreenSetting.class);
        if("success".equals(checkStatus)){
            crmLargeScreenSetting.setCheckStatus("上传成功");
        }else if("fail".equals(checkStatus)){
            crmLargeScreenSetting.setCheckStatus("上传失败");
        }else{
            crmLargeScreenSetting.setCheckStatus("上传中");
        }

        //如果当前数据为启用状态，则将其他数据的状态改为未启用
        if("是".equals(crmLargeScreenSetting.getIsEnable())){
            baseMapper.updateIsEnabled(crmLargeScreenSetting);
        }

        if(crmLargeScreenSetting.getId() != null){
            crmLargeScreenSetting.setUpdateTime(new Date());
            //编辑
            baseMapper.updateById(crmLargeScreenSetting);
        }else{
            crmLargeScreenSetting.setCreateTime(new Date());
            crmLargeScreenSetting.setCreateUserId(String.valueOf(UserUtil.getUserId()));
            crmLargeScreenSetting.setUpdateTime(new Date());
            //新增
            baseMapper.insert(crmLargeScreenSetting);
        }
    }

    @Override
    public String[] appendSearch() {
        return new String[0];
    }

    @Override
    public void setOtherField(Map<String, Object> map) {

    }

    @Override
    public CrmEnum getLabel() {
        return null;
    }

    @Override
    public List<CrmModelFiledVO> queryDefaultField() {
        return null;
    }

    /**
     * 上传文件
     *
     * @param file    文件对象
     * @param batchId batchId
     * @param type    type
     * @return entity
     */
    @Override
    @Async
    public UploadEntity upload(MultipartFile file, String batchId, String type, String isPublic) {
        if (StrUtil.isEmpty(batchId)) {
            batchId = IdUtil.simpleUUID();
        }
        UploadEntity entity = null;
        try {
//            CompletableFuture.runAsync(() -> {});
            entity = this.uploadLocal(file,batchId,type,isPublic);
            entity = this.uploadOss(file,batchId,type,isPublic);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return entity;
    }

    /**
     * 上传本地
     * @param file
     * @param batchId
     * @param type
     * @param isPublic
     * @return
     */
    public UploadEntity uploadLocal(MultipartFile file, String batchId, String type, String isPublic){
        UploadEntity entity = null;
        String key = "";
        File file1 = null;
        try {
            entity = new UploadEntity(BaseUtil.getNextId() + "", file.getOriginalFilename(), file.getSize(), batchId, isPublic);
            key = BaseUtil.getDate() + "/" + entity.getFileId() + JOIN_STR + entity.getName();
            entity.setType(UploadFileEnum.LOCAL.getConfig());
            file1 = FileUtil.writeFromStream(file.getInputStream(), "D:/upload/public/" + key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if ("1".equals(entity.getIsPublic())) {
            entity.setPath(config.getPublicUrl()+key);
        }else {
            entity.setPath(file1.getAbsolutePath());
        }
        return entity;
    }

    /**
     * 上传OSS
     * @param file
     * @param batchId
     * @param type
     * @param isPublic
     * @return
     */
    public UploadEntity uploadOss(MultipartFile file, String batchId, String type, String isPublic){
        UploadEntity entity = null;
        try {
            entity = new UploadEntity(BaseUtil.getNextId() + "", file.getOriginalFilename(), file.getSize(), batchId, isPublic);
            entity = FileServiceFactory.build().uploadFileOss(file.getInputStream(), entity);
            checkStatus = "success";

            CrmLargeScreenSetting crmLargeScreenSetting = baseMapper.queryDataBySettingValue(batchId);
            if(BeanUtil.isNotEmpty(crmLargeScreenSetting)){
                crmLargeScreenSetting.setCheckStatus("上传成功");
                this.updateById(crmLargeScreenSetting);
            }

        } catch (Exception e) {
            checkStatus = "fail";
            CrmLargeScreenSetting crmLargeScreenSetting = baseMapper.queryDataBySettingValue(batchId);
            if(BeanUtil.isNotEmpty(crmLargeScreenSetting)){
                crmLargeScreenSetting.setCheckStatus("上传chenggong");
                this.updateById(crmLargeScreenSetting);
            }
            e.printStackTrace();
        }

        return entity;
    }

    /**
     * 修改状态
     * @param checkStatus
     * @param batchId
     */
    public void updateLargeScreenSettingDataStatus(String checkStatus, String batchId){
        this.checkStatus = checkStatus;
        CrmLargeScreenSetting crmLargeScreenSetting = baseMapper.queryDataBySettingValue(batchId);
        if(BeanUtil.isNotEmpty(crmLargeScreenSetting)){
            if("success".equals(checkStatus)){
                crmLargeScreenSetting.setCheckStatus("上传成功");
            }else if("fail".equals(checkStatus)){
                crmLargeScreenSetting.setCheckStatus("上传失败");
            }else{
                crmLargeScreenSetting.setCheckStatus("上传中");
            }
            this.updateById(crmLargeScreenSetting);
        }
    }

    public FileEntity queryMp4(){
        CrmLargeScreenSetting crmLargeScreenSetting = baseMapper.queryEnableData();
        if(BeanUtil.isEmpty(crmLargeScreenSetting)){
            return null;
        }
        if(StringUtils.isNotEmpty(crmLargeScreenSetting.getSettingValue())){
            FileEntity fileEntity = adminFileService.queryOne(crmLargeScreenSetting.getSettingValue());
            if(BeanUtil.isNotEmpty(fileEntity)){
                return fileEntity;
            }
        }
        return null;
    }

    @Override
    public void deleteMp4(List<Integer> fileId) {
        crmLargeScreenSettingMapper.deleteMp4(fileId);
    }
}
